package com.pascuit.gpxhandler.server.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.pascuit.gpxhandler.server.dao.UserDao;
import com.pascuit.gpxhandler.shared.dto.GpxInfoDto;

/**
 * 
 * @author Parant
 * 
 */
@Controller
public class FileUploadController {

	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

	@Autowired
	private UserDao userDao;

	@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
	public void storeFile(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
		List<BlobKey> file = blobs.get("gpxUploadWidget");

		GpxInfoDto gpx = new GpxInfoDto();
		String blobKey = file.get(0).getKeyString();
		gpx.setSourceUrl("/gpxhandler/blobservice?blob-key=" + blobKey);
		gpx.setBlogKey(blobKey);

		userDao.saveGpx(gpx);

		// NB en local la reponse peut etre nul si le host n'est pas exactement
		// le meme que celui du client
		res.setHeader("Content-Type", "text/html");
		res.getWriter().println("<html>");
		res.getWriter().println("<script type=\"text/javascript\">");
		res.getWriter().println("function test(){");
		res.getWriter().println("window.top.uploadComplete('" + gpx.getKey() + "')");
		res.getWriter().println("}");
		res.getWriter().println("</script>");
		res.getWriter().println("<body onload='test()'");
		res.getWriter().println("</body></html>");
	}
}
